#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re
import smvn.config as cfg
from smvn.util import *

class Artifact:
    verf = re.compile(r'-\d+(\.\d+)+(-\d+)*')
    """
     to describe artifact, and supply common operation
    """
    def __init__(self, groupId="lwsf", name="sample", ver="0.0.1", compiler="", dirpath=""):
        self.files = []
        self.repo = ''
        self.grouppath = ''

        self.version = ver
        if (compiler):
            self.compiler = compiler
        else:
            self.compiler = cfg.default_compiler_id
        self.lib_path = cfg.default_lib_path

        if (dirpath == ""):
            self.groupId = groupId
            self.name = name
            self.set_groupId(groupId)
            self.set_dir()
        else:
            self.groupId = "GROUP"
            self.name = "NAME"
            self.dirpath = dirpath

    def convert_version(self, ver):
        """
         convert version string to a version list
        """
        vl1 = ver.split('.')
        if ('-' in vl1[-1]):
            nv = vl1[-1].split('-')
            vl1[-1] = nv[0]
            vl1.append(nv[1])

        vdigit = [0, 0, 0, 0]
        for i in range(len(vl1)):
            try:
                t = int(vl1[i])
                vdigit[i] = t
            except IndexError, e:
                pass
        return vdigit

    def set_ver(self, ver):
        """
         set Version string
        """
        self.version = ver

    def cmp_version(self, ver1, ver2):
        """
         compare version of two string
        """
        v1 = self.convert_version(ver1)
        v2 = self.convert_version(ver2)

        for i in range(len(v1)):
            if (v1[i] < v2[i]):
                return -1
            elif (v1[i] > v2[i]):
                return 1
        return 0

    def set_repo(self, r):
        self.repo = r

    def set_groupId(self, group):
        self.grouppath = make_grouppath(group)

    def set_dir(self):
        self.dirpath = pjoin(self.grouppath, self.name, self.version)
        self.short_dirpath = pjoin(self.grouppath, self.name)
        return self.dirpath

    def get_dir(self):
        return self.dirpath

    def get_short_dir(self):
        return self.short_dirpath

    @classmethod
    def get_file_version(self, pathname):
        """
         get origin filename of a remote filepath
        """
        m = self.verf.search(pathname)
        if (m is not None):
            return m.group(0)
        return None

    def get_short_filename(self, pathname):
        fm, fe = os.path.splitext(pathname)
        try:
            fname = fm
            if (get_file_type(fe) in ['.xml', '.log', '.md5']):
                return pathname
            rver = self.get_file_version(fm)
            if (rver is not None):
                l = len(rver)
                fname = fname[0:-l]
            if (get_file_type(fe) == '.lib'):
                l = len(self.lib_path)
                if (fname[-l-1] == '-'
                    and fname[-l:] == self.lib_path):
                    fname = fname[0:-l-1]
            return fname + fe
        except IndexError, e:
            return pathname


    def get_strict_short_filename(self, pathname):
        """
         get origin filename of a remote filepath
        """
        fm, fe = os.path.splitext(pathname)
        try:
            fname = fm
            l = len(self.version)
            if (fname[-l-1] == '-'
                and fname[-l:] == self.version):
                fname = fname[0:-l-1]

            # some extra deals with lib files
            if (get_file_type(fe) == '.lib'):
                l = len(self.lib_path)
                if (fname[-l-1] == '-'
                    and fname[-l:] == self.lib_path):
                    fname = fname[0:-l-1]
            return fname + fe
        except IndexError, e:
            return pathname

    def get_long_filename(self, name):
        """
        """
        fm, fe = os.path.splitext(name)
        if (get_file_type(fe) == '.lib'):
            #ret = fm + '-' + self.compiler + '-' + self.version + fe
            ret = fm + '-' + self.lib_path + '-' + self.version + fe
        elif (get_file_type(fe) in ['.xml', '.log']):
            ret = name
        else:
            ret = fm + '-' + self.version + fe
        return ret

    def get_remote_filename(self, name):
        return pjoin(self.dirpath, self.get_long_filename(name))

